﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;using System.Linq ;
using System.Text;
using System.Threading;
using WinnerCMS.BLL;
using WinnerCMS.BLL.GatherEngine;
using WinnerCMS.Common;
using WinnerCMS.GatherEngine;
using WinnerCMS.PlugIn.Scheduler;
namespace WinnerCMS.PlugIn.Task
{
    public class AutoGather : IScheduler
    {
        static private ManualResetEvent _synchro = null;
        static private int _threadNum = 5;
        private GatherContentPage _gc;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parameterized">参数为：ModelId,ID</param>
        public void Execute(object parameterized)
        {
            try
            {
                if (parameterized == null)
                {
                    return;
                }
                else if (parameterized.ToString().Length == 0)
                {
                    return;
                }
                string[] args = parameterized.ToString().Split(',');
                byte modelId = byte.Parse(args[0]);
                string ids = string.Empty;
                if (args.Length > 1)
                {
                    ids = args[1];
                }

                string nextCategoryUrl = string.Empty;

                AppMain appMain = new AppMain();
                CategoryGatherResult res = null;

                CategoryParameter cp = new CategoryParameter(ids, modelId, true);

                do
                {
                    if (res == null)
                    {
                        cp.NextCategoryUrl = nextCategoryUrl;
                        cp.StartUrlIndex = 0;
                        res = appMain.GatherCategoryPage(cp);
                    }
                    else
                    {
                        cp.NextCategoryUrl = nextCategoryUrl;
                        cp.StartUrlIndex = res.StartUrlIndex;
                        res = appMain.GatherCategoryPage(cp);
                    }

                    this._gc = new GatherContentPage
                    {
                        //AdminName = "CMSRoot",
                        //BadLinkNum = 0,
                        //IsTest = false,
                        //ModelId = modelId,
                        //GatherId = res.GatherId.ToString(),
                        //IsUpdate = false,
                        //IsLeech = false
                    };
                    for (int i = 0; i < res.Urls.Count(); i++)
                    {
                        Thread th = new Thread(GatherPageForThreading);

                        if (_threadNum > 0)
                        {
                            _threadNum--;

                            th.Start(res.Urls[i]);
                        }
                        else
                        {
                            _synchro = new ManualResetEvent(false);
                            _synchro.WaitOne();     //等待   
                            _threadNum--;

                            th.Start(res.Urls[i]);
                        }
                    }


                    nextCategoryUrl = res.NextCategoryUrl;

#if DEBUG

                    string FILE_NAME = WinnerCMS.Common.HttpServer.MapPath("/SchedulerJob.txt");

                    if (!File.Exists(FILE_NAME))
                    {
                        StreamWriter sr = File.CreateText(FILE_NAME);
                        sr.Close();
                    }
                    //向文件写入内容
                    using (StreamWriter x = new StreamWriter(FILE_NAME, true, System.Text.Encoding.UTF8))
                    {
                        if (string.IsNullOrEmpty(res.Err))
                        {
                            x.WriteLine(nextCategoryUrl);
                        }
                        else
                        {
                            x.WriteLine(res.Err);
                        }
                        x.Close();
                    }
#endif

                } while (nextCategoryUrl.Length > 0);
            }
            catch (Exception ex)
            {
                SchedulerLogs.WriteLog(ex.Message);
            }
        }

        private void GatherPageForThreading(object url)
        {
            this._gc.GatherPageForThreading(url);
            _threadNum++;
            if (_threadNum > 0)
            {
                if (_synchro != null)
                    _synchro.Set();//激活等待
            }
        }

    }
}